<template>
    <div>
        <el-row :gutter="20" style="margin: 0 10px;">
          <el-col :lg="8">
            <page-main title="" style="margin: 10px 0 10px 0;">
              <span>户号</span>
              <el-select class="strech" v-model="dataManager.current.mapName" placeholder="请选择" @change="handleMapChange">
                <el-option
                  v-for="map in dataManager.mapList"
                  :key="map.id"
                  :label="map.name"
                  :value="map.name">
                </el-option>
              </el-select>

        <el-collapse v-model="activeCollapse" accordion>
          <el-collapse-item title="房间列表" name="1">
            <!-- radio 选择 -->
            <el-radio-group  v-model="dataManager.current.positionName" @change="handlePositionChange">
              <el-radio v-for="(positionName) in dataManager.positionNameList" :label="positionName" :key="positionName">{{ positionName }}</el-radio>
            </el-radio-group>
          </el-collapse-item>
        </el-collapse>

        <el-divider >选择房间-在图上标记</el-divider>
        <el-button type="success"  @click="choose">选择</el-button>
        <el-button type="danger" @click="removePosition" :disabled="canvasManager.editStatus">删除</el-button>

        <el-button-group v-if="canvasManager.editStatus">
        <el-button type="success" @click="savePosition">保存</el-button>
        <el-button type="danger" @click="cancelPosition">取消</el-button>
        </el-button-group>

        <el-divider  content-position="left" >设置任务：1.完成初始化 2.选择房间 3.开始自动扫描</el-divider>
        <el-button type="success" @click="dialogFormVisible  = true" >自动检测</el-button>
        <el-button type="primary" @click="showPosition">显示位置</el-button>
     
        <el-dialog title="创建扫描任务" :width="$store.state.settings.mode == 'pc' ? '' : '90%'" :visible.sync="dialogFormVisible">
         <el-form :model="dynamicValidateForm" ref="dynamicValidateForm" :label-width="$store.state.settings.mode == 'pc' ? '150px' : ''" >
          <el-form-item
            v-for="(domain, index) in dynamicValidateForm.domains"
            :label="'房间' + (index+1)"
            :key="domain.key"
            :prop="'domains.' + index + '.value'"
            :rules="{
              required: true, message: '房间不能为空', trigger: 'blur' 
            }"
          >
          <el-select v-model="domain.value" placeholder="请选择房间">
                <el-option  v-for="(positionName) in dataManager.positionNameList" :label="positionName"  :value="positionName" :key="positionName"></el-option>
          </el-select>
          <el-button @click.prevent="removeDomain(domain)">删除</el-button>
          </el-form-item>
       
          <el-form-item > 
              <el-button type="primary" @click="submitForm('dynamicValidateForm')">创建并开始</el-button>
              <el-button @click="addDomain">添加房间</el-button>
              <el-button @click="resetForm('dynamicValidateForm')">重置</el-button>
              <el-button @click="dialogFormVisible = false">取 消</el-button>
          </el-form-item>

          </el-form>
          <div slot="footer" class="dialog-footer">
          </div>
        </el-dialog>
   
        <el-divider content-position="left" >任务操作<i style="color: crimson;">（任务停止后无法继续扫描，请慎用）</i></el-divider>
        <el-button type="primary" @click="pauseTask" :disabled="canvasManager.editStatus">暂停</el-button>
        <el-button type="primary" @click="resumeTask" :disabled="canvasManager.editStatus">恢复</el-button>
        <el-button type="danger" @click="stopAllTask">停止</el-button>
      
        </page-main>
        </el-col>

        <el-col :lg="16">
            <page-main title="" style="margin: 10px 0 10px 0;" id="mapcover">
                <div class="question">
                      <canvas id="map" class="map"></canvas>
                </div>
            </page-main>          
        </el-col>
        </el-row>
        <el-dialog title="提示" :visible.sync="progressBar.initDialogVisible" width="30%" :modal="true" :show-close="false" 
          :close-on-click-modal="false" :close-on-press-escape="false" center lock-scroll 
        >
        <div style="text-align: center;">
          <!-- <el-progress v-if="progressVisible" type="circle" :percentage="progressBar.percentage" :width="150" :status="progressBar.progressStatus"></el-progress> -->
          <div v-if="closeStatus">小车正在前往房间</div>
          <div v-if="closeStatus" style="clear: both; margin-top: 10px;">{{this.webSocket.taskStatus.statusCode}}:{{this.webSocket.taskStatus.statusMsg}}</div>
          <div v-if="scanningStatus" style="clear: both;">小车正在进行扫描</div>
          <div v-else-if="progressBar.percentage==100" style="clear: both;">该房间扫描完成</div>
        </div>
          <span slot="footer" class="dialog-footer">
            <el-button v-if="progressBar.percentage<100" type="danger" @click="closeDialog();">中止扫描</el-button>
            <!-- <el-button v-else-if="progressBar.percentage==100" type="success" @click="closeDialog();">确认</el-button> -->
          </span>
        </el-dialog>
    </div>
    
</template>

<script>
import CanvasManager from '@/static/CanvasManagerPosition';
import DataManager from '@/static/DataManagerTask';
import msApi from "@/api/msApi";
import gsApi from "@/api/gsApi";
import ProgressBar from '@/static/ProgressBar';
import WebSocket from '@/static/WebSocket';

  export default {
    name: "test",
    data() {
      return {
        check_task:'',
        check_scan:'',
        canvasManager:'',
        dataManager:new DataManager(),
        activeCollapse:'1',
        dialogFormVisible: false,
        dynamicValidateForm: {
          domains: [{
            value: '',
          }],
        },
        progressBar:new ProgressBar(),
        progressVisible:false,
        currentItem:null,
        webSocket:new WebSocket(),
        closeStatus:true,
        scanningStatus:false
      }
    },
    created(){
    },
    mounted() {
      this.loadData();
      this.preventScroll();
      this.webSocket.startWebSocket();
    },
     destroyed(){
      clearPositionInterval()
    },
    methods:{
      async loadData(){
        await this.dataManager.loadMaps();
        await this.dataManager.location();
        await this.dataManager.loadPositions(this.dataManager.mapList[0].name);
     
        // 这里需要等待数据加载完后，再初始化canvasManager。因为需要知道第一张地图的名字，用作显示
        this.canvasManager=new CanvasManager({
          canvasId:'map',
          mapName:this.dataManager.mapList[0].name,
        })
        this.showPosition();
      },
      handleMapChange(mapName){
        this.canvasManager.reloadImg(mapName);
        this.dataManager.loadPositions(mapName);
      },

      choose() {  
        this.$message.info("请在地图上标记点")
        this.canvasManager.clearObjectCircle();
        this.canvasManager.clearObjectText();
        this.canvasManager.editStatus=true;
        this.canvasManager.clickStatus=true;
      },
      closeDialog(){
        this.progressBar.initDialogVisible=false
      },
      savePosition(){
        // 根据再canvas上 打的点，生成要提交的数据
          let positionBean=this.canvasManager.generatePosition();
          if(positionBean.name==undefined){
            this.$message.error("请先在图片上打点")
            return 
          }
          //向机器人中发送保存定点的请求
          this.$prompt('请输入定点名称', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            inputPattern:/^[\u4E00-\u9FA5A-Za-z0-9_]+$/,
            inputErrorMessage: '只能输入英文/数字/汉字'
          }).then(async({ value }) => {
              positionBean.name = value;
              try{
                const res=await gsApi.insertPosition(positionBean);
                if(res.data.msg==='successed'){
                  this.$message.success("房间"+positionBean.name+'保存成功')
                  // 保存成功后，重新加载路径数据，并且选中新添加的路径
                  await this.dataManager.loadPositions(this.dataManager.current.mapName);
                  this.dataManager.current.positionName=positionBean.name;
                  this.canvasManager.editStatus=false;
                }else{
                  this.$message.error("出现问题" + res.data.msg)
                }
              }
              catch(err){
                console.log(err)
                this.$message.error("出现异常，详见控制台")
              }
          }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        });       
      });
      },

      removePosition(){
          const positionName=this.dataManager.current.positionName;
          const mapName=this.dataManager.current.mapName;
          if(positionName === ''){
            this.$message.error('房间为空')
            return
          }
        this.$confirm('此操作将永久删除该房间, 是否继续?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(async() => {
              try{
                const res = await gsApi.deletePosition(mapName, positionName)
                console.log(res)
                if(res.data.msg==='successed'){
                  this.$message.success('房间' + positionName + '删除成功')
                  this.dataManager.loadPositions(mapName);     
                  this.dataManager.current.positionName = ''    
                  this.canvasManager.clearObject();
                }else{
                  this.$message.error("删除定点失败，详见控制台")
                }
              }catch (err) {
                console.log(err);
                this.$message.error('删除失败，详见控制台')
              }
            }).catch(() => {
                this.$message({
                  type: 'info',
                  message: '已取消删除'
                });          
              });     
         },
        cancelPosition(){
          // 清理canvas 暂存的打点数据
          // this.canvasManager.clearObject(); // 清理地图路径
          this.canvasManager.clearObjectCircle();
          this.canvasManager.clearObjectText();
          this.canvasManager.tempPoints=[];
          // 退出编辑状态
          this.canvasManager.clickStatus=false;
          this.canvasManager.editStatus=false;
          //清空tempPosition信息，以免点保存的时候误保存最后一次遗留的点
          this.canvasManager.tempPosition={};
          // 重新绘制选中的路径
          //this.handlePositionChange(this.dataPosition.current.positionName);
        },

        handlePositionChange(positionName){
          this.canvasManager.clearObjectCircle();
          this.canvasManager.clearObjectText();
          this.canvasManager.drawPosition({positionName,dataManager:this.dataManager});
        },
   
       removeDomain(item) {
        var index = this.dynamicValidateForm.domains.indexOf(item)
        if (index !== -1) {
          this.dynamicValidateForm.domains.splice(index, 1)
        }
      },
      addDomain() {
        this.dynamicValidateForm.domains.push({
          value: '',
          key: Date.now()
        });
      },

      resetForm(formName) {
          this.$refs[formName].resetFields();
      },

      submitForm(formName) {
        this.$refs[formName].validate(async(valid) => {
          if (valid) {
              try {
                const mapName=this.dataManager.current.mapName            
                const domains = this.dynamicValidateForm.domains
                for(let i = 0;i<domains.length;i++)
                {
                    this.dataManager.pointer[i] = domains[i].value //把点序列存入pointer中
                }
                // const taskBean= gsApi.createTaskBean(mapName,taskName,this.dataManager.pointer);//构造任务形式
                // const res= await gsApi.createTaskQueue(taskBean);//创建任务
                  this.dialogFormVisible = false            
                  this.$message.success("任务"+mapName+'创建成功,即将开始')                
                  this.startTask(mapName);
              }catch (err) {
                  console.log(err);
                  this.$message.error('网络异常')
              }
              }else{
              return false;
            }
          });
        },

        //扫描任务中的开始任务，利用定点导航
        async startTask(mapName){
         if(mapName=== ''){
           this.$message.error('地图出错')
           return
         }
         try {
            this.progressBar.initDialogVisible=true;
            let item = this.dataManager.current.item;//下一个目标点索引
            for(let i = item;i<this.dataManager.pointer.length;i++){
              /**新的周期，进度条归零，导航行驶中进度条不可见**/
              // this.progressVisible = false
              // this.progressBar = 0
              // this.currentItem = i
              /*********************************************/
              let positionName = this.dataManager.pointer[i]
              let res = await gsApi.startNavigate(mapName,positionName)
              let taskId = Date.parse(new Date())
              if(res.data.msg==='successed'){
                this.$message.success(`开始前往${positionName}`)
                await this.checkTask(taskId,mapName,positionName)
                await this.checkScan(taskId,positionName)
              } else {
                this.$message.error(res.data.msg);
              }
            }
            clearInterval(this.check_task)
            clearInterval(this.check_scan)
            this.comeBack()
          }catch (err) {
           console.log(err);
           this.$message.error('网络异常')
         }
      },

      //每隔5秒查询是否导航成功，完成了当前任务则发送开始扫描的请求
      async checkTask(taskId,mapName,positionName){
          await new Promise((resolve, reject) => {
          this.check_task =  setInterval(async() => {
                let res_task  = await gsApi.checkTask();
                if(res_task.data.data === true)//导航完成
                {
                  this.closeStatus=false
                  this.scanningStatus=true
                  let param = []
                  clearInterval(this.check_task);
                  this.dataManager.current.item ++ 
                  param['taskId']  = taskId
                  param['suite'] = mapName
                  param['room'] = positionName
                  await msApi.scan(param)
                  this.$message.success(`开始扫描${positionName}`)
                  resolve()
                }
            },5000);
          })
      },

       async checkScan(taskId,positionName){
          await new Promise((resolve, reject) => {
           this.check_scan =  setInterval(async() => {
                let res_scan  = await msApi.queryState(taskId);
                /**扫描开始，进度条开始工作**/
                // this.progressVisible = true
                // this.progressBar.taskProgress(30)
                /**************************/
                if(res_scan.data.data.state === 'finished')//扫描完成
                {
                  /**完成剩余进度条**/
                  // this.progressBar.finishRest()
                  /*****************/
                  clearInterval(this.check_scan)
                  this.$message.success(`扫描完成${positionName}`)
                  // console.log('第'+ this.dataManager.current.item +'次扫描结束')
                  await msApi.submitRules(taskId)
                  resolve()
                }
              }, 15000);
          })
      },

      async pauseTask(){
              try {
                const res = await gsApi.pauseTask();
                if(res.data.msg==='successed'){
                  this.$message.success(`暂停任务`)
                  clearInterval(this.check_task)
                  clearInterval(this.check_scan)
                }else{
                this.$message.error(res.data.msg);
                }
              }catch (err) {
                console.log(err);
                this.$message.error('网络异常')
              }
          },

       async resumeTask(){
         try {
            const mapName=this.dataManager.current.mapName
            this.startTask(mapName);    
         }catch (err) {
           console.log(err);
           this.$message.error('网络异常')
         }
      },

        async stopAllTask(){
        try {
          const res = await gsApi.stopAllTask()
          if(res.data.msg==='successed'){
            this.$message.success('停止任务成功')
            clearInterval(this.check_task)
            clearInterval(this.check_scan)
          }else{
            this.$message.error(res.data.msg);
           }
        }catch (err) {
          console.log(err);
          this.$message.error('网络异常')
        }
      },

       async comeBack(){
        const mapName=this.dataManager.current.mapName;
         try {
           const res = await gsApi.startNavigate(mapName,'Origin');
           if(res.data.msg==='successed'){
             this.$message.success(`正在返回`)
           }else{
            this.$message.error(res.data.msg);
           }
         }catch (err) {
           console.log(err);
           this.$message.error('网络异常')
         }
      },
      async showPosition(){
        await this.dataManager.location()
        console.log(this.dataManager.loadPoint)
        this.canvasManager.showCurrentPosition(this.dataManager.loadPoint);
        clearInterval(this.intervalFlag)
        this.intervalFlag = setInterval(async () => {
            //const res = await gsApi.getLocation()
            //不能直接这样写，会报错
            await this.dataManager.location();
            this.canvasManager.moveCurrentPosition(this.dataManager.loadPoint);
          }, 500);
      },
      preventScroll(){
        let mapcover = document.getElementById("mapcover");
        console.log('执行了')
        mapcover.onmouseout = ()=>{
          document.documentElement.style.overflow='auto';
        }
        mapcover.onmouseover = ()=>{
          document.documentElement.style.overflow='hidden';
        }
      },
       clearPositionInterval(){
        clearInterval(this.intervalFlag)
      }
    }
  }
</script>